package com.ynu.yx.chatroleai.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ynu.yx.chatroleai.dao.UserDao;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ThreadLocalRandom;

@Component
public class IdGenerator {
    /**
     * 生成一个独一无二的 uid
     * 格式：六位数字
     * @return 生成的 uid
     */
    public <T> Long generateUniqueId(BaseMapper<T> dao, String fieldName) {
        Long id;
        do {
            id = generateId();
//            System.out.println("循环中");
        } while (!isIdUnique(dao, fieldName, id));
        return id;
    }

    /**
     * @return 生成的 uid
     */
    private Long generateId() {
        long timestamp = System.currentTimeMillis(); // 获取当前时间戳
        long randomPart = ThreadLocalRandom.current().nextInt(100000, 1000000); // 生成六位随机数
        return (timestamp % 1000000L) + randomPart; // 结合时间戳和随机数
    }


    private <T> boolean isIdUnique(BaseMapper<T> dao, String fieldName, Object fieldValue) {
        if (dao == null) {
            throw new IllegalStateException("Dao 未被正确注入，请检查配置");
        }
        // 使用MyBatis-Plus的QueryWrapper构建查询条件
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(fieldName, fieldValue);

        // 调用对应的Dao方法查询记录数
        return dao.selectCount(queryWrapper) == 0;
    }

}
